Repository navigation
Conversation
|
Size Change: +4.16 kB (+0.05%) Total Size: 7.92 MB 📦 View Changed
|
There was a problem hiding this comment.
Pull request overview
Refactors the media editor crop implementation so the advanced crop panel, bottom toolbar, and cropper/provider share centralized primitives for crop geometry, derived measurements, and fine rotation policy—reducing duplicated math and simplifying UI state handling.
Changes:
- Introduces shared derivation/geometry primitives (
useDerivedCropperMeasurements,useCropGeometry,core/crop-geometry,core/fine-rotation) and updates consumers to use them. - Reworks advanced crop inputs around
useDeferredCommitanduseAdvancedCropControls, makingCropInput/panel components mostly render-only. - Updates toolbar fine-rotation behavior to use the shared
fineRotationpolicy and updates server modifier building to usegetCropPixelRect.
Reviewed changes
Copilot reviewed 24 out of 24 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/media-editor/src/image-editor/react/hooks/use-derived-cropper-measurements.ts | New shared hook to derive element/visual sizes + crop bounds from state + canvas size. |
| packages/media-editor/src/image-editor/react/hooks/use-crop-geometry.ts | New hook exposing pixel crop geometry snapshot from provider state + measurements. |
| packages/media-editor/src/image-editor/react/hooks/test/use-crop-geometry.tsx | Adds unit tests for useCropGeometry readiness and snapshot values. |
| packages/media-editor/src/image-editor/react/components/index.ts | Exports useCropperMeasurements and CropperMeasurements from the components barrel. |
| packages/media-editor/src/image-editor/react/components/cropper.tsx | Switches cropper to use the shared derived measurements hook and publishes canvas size to provider. |
| packages/media-editor/src/image-editor/react/components/cropper-provider.tsx | Expands provider context to include controller + measured canvas size + derived measurements, plus helper hooks. |
| packages/media-editor/src/image-editor/docs/recipes.md | Documentation updates (code fences, spacing, heading numbering tweaks). |
| packages/media-editor/src/image-editor/core/test/crop-geometry.ts | Adds unit tests for new crop-geometry helpers (snapshot, validation, clamping, edits). |
| packages/media-editor/src/image-editor/core/index.ts | Re-exports crop geometry helpers/types and fine rotation policy from core. |
| packages/media-editor/src/image-editor/core/fine-rotation.ts | New shared fine rotation policy (range/step, offset conversion, safe absolute conversion). |
| packages/media-editor/src/image-editor/core/crop-geometry.ts | New shared crop pixel geometry conversion/validation/editing utilities. |
| packages/media-editor/src/components/media-editor-toolbar/index.tsx | Uses shared fineRotation for fine rotation slider offset + commits. |
| packages/media-editor/src/components/media-editor-modal/style.scss | Adds styling to align advanced crop panel layout within the modal sidebar panel. |
| packages/media-editor/src/components/media-editor-modal/build-modifiers.ts | Uses getCropPixelRect for snap-rotation crop pixel math when building REST modifiers. |
| packages/media-editor/src/components/media-editor-crop-panel/use-deferred-commit.ts | New hook implementing draft/commit/finalize behavior for numeric inputs (Enter/Escape/blur). |
| packages/media-editor/src/components/media-editor-crop-panel/use-advanced-crop-controls.ts | New hook wiring advanced crop panel inputs to cropper state + geometry + policies. |
| packages/media-editor/src/components/media-editor-crop-panel/test/use-deferred-commit.tsx | Unit tests for deferred commit behavior and edge cases. |
| packages/media-editor/src/components/media-editor-crop-panel/test/use-advanced-crop-controls.tsx | Unit tests for advanced crop control ranges and edit/rotation behavior. |
| packages/media-editor/src/components/media-editor-crop-panel/test/crop-input-utils.ts | Unit tests for range/bounds/step snapping helpers. |
| packages/media-editor/src/components/media-editor-crop-panel/test/crop-advanced-panel.tsx | Integration-style tests for advanced panel input behavior (typing, clamping, settle/history). |
| packages/media-editor/src/components/media-editor-crop-panel/index.tsx | Mounts the new CropAdvancedPanel and passes resolved aspect ratio + flags. |
| packages/media-editor/src/components/media-editor-crop-panel/crop-input.tsx | New renderer-only numeric input component using useDeferredCommit. |
| packages/media-editor/src/components/media-editor-crop-panel/crop-input-utils.ts | New utilities for numeric input range/bounds and commit snapping/clamping. |
| packages/media-editor/src/components/media-editor-crop-panel/crop-advanced-panel.tsx | New advanced panel markup component powered by useAdvancedCropControls. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
Flaky tests detected in 6a8a744. 🔍 Workflow run URL: https://github.com/WordPress/gutenberg/actions/runs/33351554074 should allow user to add and remove multiple local font files in
|
d8dc3b5 to
33f1bbd
Compare
|
Undo/redo isn't consistent at the moment. Looking into that. |
There was a problem hiding this comment.
Nice progress! Just a quick drive-by comment while I was testing the UX. In the main it's feeling really good to me, as we were discussing in the other PR.
I think I found one slighty strange edge case if using a mouse wheel within the Y field while the image is rotated. I found it's possible for the viewport to slide right away 😄
2026-05-12.17.23.16.mp4
It only seems to occur when the image has a fine rotation applied, not sure if that helps narrow things down!
In terms of adding pauseHistory and resumeHistory that does sounds really useful for cases beyond just what we're dealing with in these controls. While testing this out with an LLM, one question came up and that's whether we could simplify to just a pauseHistory method, but have it return a function to resume history?
E.g. something like:
// Today — two calls, easy to drift apart
pauseHistory();
// ...
resumeHistory();
// RAII-style — release is the return value of acquire
const resume = pauseHistory();
// ...
resume();
I had to look up what RAII means, and in this case I think Claude was maybe being a bit too clever in its explanation. But I think the point was something along the lines of, with this approach "the lifetime of the paused state is the lifetime of the callback". In any case, just thought I'd mention it in case it simplifies things at all, but feel free to disregard, especially if you think resuming needs to be independent!
I'll give this PR a closer look tomorrow 👍
Oh yes, I can reproduce 😅 Thanks for testing again! I'm going to take a step back and check if this feature has drifted into overengineering. I think the trap I'm falling into is that I'm trying to make live edits behave like drag/resize. Text fields aren't crop handles, and it gets chaotic to try to predict and avoid every correction from the panel. I think the base is sound:
I'll just experiment to see whether there's another UX path here that doesn't explode the combo of wheel + bounds + canvas representation 🤔 |
Same. For what it's worth, in this PR the UX you got to feels really good aside from that bug! |
|
I committed an idea I had to preserve image bound values in the advanced controls, and remove all the complexity of trying to match drag handler behaviour: create a preview area for advanced controls. Screencast in the PR description. So advanced crop fields no longer mutate the real cropper on every keystroke, but show a preview overlay while editing. The commit only happens onBlur/Enter. That lets the fields use image bounds like drag handles, without pushing the canvas off-screen mid-edit, and also removes the need for canvas-bound manual ranges and most of the live-edit/history edge cases. |
| export const fineRotation = { | ||
| step: 0.5, | ||
| min: -MAX_ROTATION_OFFSET, | ||
| max: MAX_ROTATION_OFFSET, | ||
|
|
| label={ __( 'X' ) } | ||
| aria-label={ __( 'Crop horizontal position' ) } | ||
| value={ rect.left } | ||
| range={ ranges.left } | ||
| disabled={ | ||
| ! canMoveCropRect || ! ranges.left.isEditable | ||
| } | ||
| commitOnChange={ false } |
Neat idea! From a quick play that seems to be working quite nicely, especially for that bug. Couple of questions:
Overall though, the idea that the advanced controls render an optimistic view of what it might look like before committing, sounds like a pragmatic way to solve this! |
Yes styling was the thing I left last. Good idea!
Egad. I did specifically say to document everything, so I'll see how much of that is comments+docs and what can be purged. Thanks again! 🙇🏻 |
Did a quick looksy:
Tests make up 49% of the PR 🙃 |
That's a good thing, better than it all being production code! I don't mind heaps of tests 😄 Let me know when you'd like some 👀 on the code side of things and I can take a peek. |
Thank you! I'm going to remove some duplication, and then work on the updated styles you recommended. Shan't be long! |
9bf22eb to
6b0451d
Compare
6b0451d to
6a8a744
Compare
Adds an Advanced panel to the media editor crop sidebar with manual
controls for X, Y, width, height, and fine rotation. Controls update the
crop preview as the user types; the displayed value stays sovereign while
focused and clamps to bounds on blur or Enter.
Geometry API (core, internal):
- applyCropEdit(rect, field, value, { aspectRatio, bounds }) — single
entry point for an edit + aspect-ratio couple + bound clamp, with an
aspect-ratio-aware envelope so a locked-ratio edit cannot drift the
ratio when one axis exceeds the image.
- getCropPixelRect / cropPixelRectToNormalizedRect /
clampCropPixelRectToBounds — pixel-space helpers.
- validateCropPixelRectAgainstBounds — { ok: true | false } diagnostic
result for automation / AI consumers.
- fineRotation policy — shared by the bottom toolbar ruler and the
advanced panel. Pulls offsets strictly inside ±MAX_ROTATION_OFFSET to
prevent the snap-base spiral on repeated edits.
React layer:
- CropperProvider holds one context with the controller, the measured
canvas size, and the derived measurements.
- useDerivedCropperMeasurements is the single derivation hook used by
the Provider and by <Cropper>.
- useDeferredCommit owns the focused-draft state machine. While focused,
the input is sovereign: external state changes (settle, sibling
commits, undo/redo) do not replace the typed draft, and out-of-range
drafts stay editable. Dirty drafts clamp and commit once on blur or
Enter; Escape rolls back to the focus-time value.
- useAdvancedCropControls supplies the panel's data and handlers.
- <Cropper> publishes raw canvas size into the Provider; nothing pushes
derived state back through a sibling context.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds pauseHistory / resumeHistory to useCropperState so input-driven edit sessions no longer accumulate intermediate undo entries on typing pauses. Wires the new pair through useDeferredCommit, CropInput, and useAdvancedCropControls: focus pauses the auto-history debounce, blur/Enter resumes it, and the session's single entry lands via the existing settleCrop -> commitHistory path. useDeferredCommit cleans up an active session on unmount so a modal close mid-edit flushes any pending commit and releases the pause. useCropperState routes all reducer dispatches through a dispatchAction wrapper that mirrors the reducer result into stateRef synchronously, so same-tick setter + commitHistory sequences see the right state. The reducer must stay pure (called again when React commits).
Restyles the panel-driven preview rect to match the real stencil and moves the dimming and rule-of-thirds grid to follow it. While a preview is active the stencil itself is hidden (opacity: 0) and the preview stands in for it, so a user typing into the panel sees "the crop moved" rather than "a new dashed rectangle appeared on top of the crop". Also drops about 280 lines of duplicated test coverage. The panel test no longer re-runs behaviour already covered at the hook level (fine rotation policy, pause/resume bracketing, near-integer drift, external state changes). The deferred-commit unmount + session-end-once tests collapse into one parameterised test each.
Adds a new function, normalizeOffsetForDisplay, to ensure that the fine rotation offset is correctly normalized for user display. This change prevents discrepancies between the internal representation and the public endpoint of ±45°. The offsetFromState method is updated to utilize this new normalization function, enhancing the accuracy of rotation adjustments in the media editor.
…Enter key behavior - Updated the onBlur function to use a local variable for clarity. - Enhanced the logic to ensure previews are cleared correctly when Enter triggers a blur event. - Added a new test case to verify that deferred previews are cleared as expected upon Enter key press.
…just border properties for the advanced crop panel. This change enhances the visual alignment of the panel within the media editor interface.
The use-recommended-components lint rule rejects Flex and FlexItem from @wordpress/components. The two-input rows (X/Y, Width/Height) now use Stack from @wordpress/ui, with a stylesheet rule giving each input an equal share of the row (what FlexItem isBlock did). The single Fine rotation input no longer needs a row wrapper: as a direct child of the column Stack it already stretches to full width.
trunk removed the /** WordPress dependencies */ separators repo-wide and turned on @wordpress/dependency-group and import/order (#81248), so the import blocks in the files this branch adds no longer pass lint. Remove the separator comments and the blank lines between import groups.
trunk now picks the unit test environment from the filename (#80991) and typechecks test files through the split dev tsconfig (#81515). Rename the four tests that need a DOM to *.jsdom.test.tsx, and hold the narrowed controls in a const in use-advanced-crop-controls so the isReady check still applies inside the act callbacks.
The panel layout refactor (#81840) replaced the ComplementaryArea wrapper with a Tabs panel, so .media-editor__sidebar-panel no longer exists and the rule that strips PanelBody's border and padding stopped matching. Target .media-editor__panel, the class the pane now carries.
The session boundary (#83550) moved the cropper controller under session.cropper, so state, setCropRect, setRotation and settleCrop no longer sit at the top level of what useMediaEditor() returns. Read them from the cropper, keep beginGesture and endGesture on the session, and hand CropperProvider the cropper rather than the whole session.
The repository finished its Jest to Vitest migration (#82211, #80995, #82742) and dropped the Jest globals, so these tests import describe, it and expect, call vi in place of jest, and use the typed vi.mock( import( … ) ) form the conventions check requires. The crop panel mocks also follow the session shape. In the cropper suite, which trunk moved to Browser Mode, the ported preview and unmount tests render through renderCropper and click with userEvent.
The upgrade (#82731) rewraps a union type and an indent in these two files.
6a8a744 to
1b8b59c
Compare
🤖 PR meta 🤖🎉 PropsIf you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message. To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. Updated as activity occurs, without notifying anyone named here. Add the 📦 Bundle sizeSize Change: +4.57 kB (+0.06%) Total Size: 8.26 MB 📦 View Changed
⚡ PerformanceShow the resultsClient side metrics exclude the server response time. front-end-block-theme
front-end-classic-theme
media-processing
media-upload
post-editor
site-editor
|
The crop panel already disables the transform controls and the aspect ratio select while a save runs (#82417), but the Advanced fields stayed live, so a crop could be typed into an edit that was on its way to the server. Pass the flag down and combine it with each field's own editability test.
What
Kapture.2026-06-10.at.16.08.40.mp4
Part of:
Alternative to:
Adds an Advanced panel to the media editor crop sidebar with manual controls for X, Y, width, height, and fine rotation.
While a numeric field is focused, the cropper paints a non-interactive preview rectangle for the candidate crop; the real
setCropRectfires on blur or Enter. Fine rotation stays live because visual feedback on the image itself is the point.
Why
The crop sidebar previously had no way to enter precise pixel values. The natural live-commit approach (apply the edit on every keystroke) made the cropper auto-pan/zoom to fit the new crop, which felt like the viewport sliding out from under the user as they typed. Painting a preview rect instead keeps the canvas stable while editing and finalises in one step at the natural completion boundary.
How
CropPreviewOverlayon the cropper. The Provider holds apreviewCropRectslot that panel controls publish; the cropper renders the rectangle and dims the live stencil while a preview is active.useDeferredCommithook drives the input lifecycle: live-commit by default, preview-only whencommitOnChangeis false. While focused, the typed value is sovereign and external state changes do not overwrite it. Blur, Enter, or Escape clamps and commits in one step; Escape rolls back.useAdvancedCropControlshook resolves geometry, computes per-field ranges, and exposes commit + preview handlers. Width/height ranges anchor to the current crop edge so coupled aspect-ratio edits cannot push the crop off the image.pauseHistoryonuseCropperState: input-driven sessions pause the auto-history debounce on focus and resume on blur, so a focus session lands as one undo entry rather than one per typing pause. Returns an idempotent resume callback. The cropper reducer now routes through adispatchActionhelper that mirrors reducer results synchronously, so same-event setter + commitHistory sequences see the right state.fineRotationpolicy in core. The bottom toolbar ruler and the advanced panel fine-rotation field both use it; offsets are pulled inside ±45 by a small epsilon so committing the boundary does not flip the snap base and let the rotation spiral past its intended range.applyCropEditin core/crop-geometry. Single entry point for edit + aspect-ratio couple + clamp, with an aspect-ratio-aware envelope so locked-ratio edits cannot drift.validateCropPixelRectAgainstBoundsreturns a{ ok: true | false }discriminated union; the symbol-brandedCropPixelRectand the'precision-clamped'violation are gone.CropperProvidercollapses to one context with the controller, the measured canvas size, and the derived measurements.<Cropper>publishes the raw canvas size; nothing pushes derived state back through a sibling context.Manual testing
Use of AI
Mucho